import axios from 'axios';
import {interfaceUrl} from '@/utils/publicUrl';
import {Notify, Toast} from 'vant';
import Router from '../router';

// import store from '@/store';
let toast = false
// create an axios instance
const service = axios.create({
	baseURL: process.env.NODE_ENV === 'production' ? interfaceUrl : '/api',
	timeout: 20000, // request timeout
	headers: {
		'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
		// 'Content-Type': 'application/json; charset=UTF-8'
		// 'Content-Type': 'text/html; charset=UTF-8'
	}
})

service.interceptors.request.use(
	config => {
		
		config.headers = {
			linkRefer: Router.currentRoute.fullPath,
		}
		
		if (config.method === 'post' || config.isSlow) {
			toast = Toast.loading({
				mask: true,
				forbidClick: true,
				duration: 0,
				message: 'loading...'
			});
		// } else {
		// 	Toast.loading({
		// 		mask: false,
		// 		forbidClick: true,
		// 		duration: 600,
		// 		message: 'loading...'
		// 	});
		}
		// POST
		// 默认为 Content-Type: application/x-www-form-urlencoded
		// 接口单独配置的为 Content-Type: application/json; charset=utf-8
		if (config.method === 'post') {
			if (config.headers['Content-Type'] === 'application/x-www-form-urlencoded') {
				config.transformRequest = [function (data) {
					// 将数据拼接
					let ret = '';
					for (let it in data) {
						ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
					}
					return ret;
				}];
			}
		}
		return config
	},
	error => {
		if (toast) {
			toast.clear();
		}
		// do something with request error
		console.log(error) // for debug
		return Promise.reject(error)
	}
)
// response interceptor
service.interceptors.response.use(
	response => {
		if (toast) {
			toast.clear();
		}
		const res = response.data
		if (response.status !== 200) {
			Notify({
				message: res.msg || 'error',
				duration: 3000,
				background: '#fa4e63'
			});
			return Promise.reject('网络错误，稍后再试！' || res.msg || 'error')
		} else {
			return res
		}
	},
	error => {
		if (toast) {
			toast.clear();
		}
		console.log('err' + error) // for debug
		Notify({
			message: '网络错误，稍后再试！' || error.message || 'error',
			duration: 3000,
			background: '#fa4e63'
		});
		return Promise.reject(error)
	}
)

export default service
